package dexter.net;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;

import dexter.net.msg.RequestMessage;
import dexter.net.msg.ResponseMessage;
import dexter.net.msg.BusMessage;
import dexter.net.msg.common.RequestListener;
import dexter.net.msg.common.ResponseParams;
import dexter.net.msg.common.BusListener;

public class ConsumerSessionHandler extends IoHandlerAdapter {
    
	private RequestListener reqListener;
	private BusListener routeListener;
	
	public ConsumerSessionHandler(RequestListener listener) {
		this.reqListener=listener;
	}

	public ConsumerSessionHandler(BusListener listener) {
		this.routeListener=listener;
	}
	
	public void sessionOpened(IoSession session) {
    	
        // set idle time to 6000 seconds
        //session.setIdleTime(IdleStatus.BOTH_IDLE, 6000);

        // initial sum is zero
        //session.setAttachment(new Integer(0));
    }

    public void messageReceived(IoSession session, Object message) {
        //TODO: CHECK MESSAGES 
    	
    	  if (message instanceof BusMessage) {
    		  
    		  BusMessage msg = (BusMessage) message;
    		  
    		  try {
    		    routeListener.receive(msg);
    		  } catch(Exception e) {
    			  e.printStackTrace();
    		  }
    	  }
    	  
          else if (message instanceof RequestMessage) {
          
            RequestMessage req = (RequestMessage) message;
            ResponseMessage res = new ResponseMessage();  
          
            try {
              ResponseParams result = reqListener.service(req.getParams());
            
              res.setResult(result);
              res.setOk(true);
            } catch (Exception e) {
        	res.setOk(false); 
        	res.setError(e);
          }
          
          session.write(res);
          
    	}  
     
    }

    public void sessionIdle(IoSession session, IdleStatus status) {
        SessionLog.info(session, "Disconnecting the idle.");
        // disconnect an idle client
        session.close();
    }

    public void exceptionCaught(IoSession session, Throwable cause) {
        // close the connection on exceptional situation
        session.close();
    }
}